/*
 * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef OHOSDEC_COMMON
#define OHOSDEC_COMMON

#include <multimedia/player_framework/native_avbuffer.h>
#include <multimedia/player_framework/native_avbuffer_info.h>
#include <multimedia/player_framework/native_avformat.h>

#include "mediastreamer2/msvideo.h"

#include <string>

#include "hilog/log.h"

namespace ohos {
#define AVCODEC_CHECK(condition, msg, retval)                                                                          \
	({                                                                                                                 \
		if ((condition)) {                                                                                             \
			OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "MMMMMMCODEC", (msg));                                        \
			return (retval);                                                                                           \
		}                                                                                                              \
	})

enum FormatType {
	FORMAT_TYPE_IMAGE_WIDTH,
	FORMAT_TYPE_IMAGE_HEIGHT,
	FORMAT_TYPE_VIDEO_STRIDE,
	FORMAT_TYPE_SLICE_HEIGHT,
	FORMAT_TYPE_PIXEL_FORMAT,
	FORMAT_TYPE_CROP_TOP,
	FORMAT_TYPE_CROP_BOTTOM,
	FORMAT_TYPE_CROP_LEFT,
	FORMAT_TYPE_CROP_RIGHT,
	FORMAT_TYPE_VIDEO_WIDTH,
	FORMAT_TYPE_VIDEO_HEIGHT,
	FORMAT_TYPE_NBR
};

enum ErrCode {
	ERRCODE_OK = 0,
	ERRCODE_UNKNOWN = -1,
	ERRCODE_PARAM_INVALID = -2,
	ERRCODE_DECODE_ERRSTAT = -3,
	ERRCODE_QUEUE_EMPTY = -4,
	ERRCODE_TIMEOUT = -5
};

struct VideoFormat {
	std::string codecMime{"video/avc"};
	int32_t width{0};
	int32_t height{0};
	int64_t bit_rate{0};
	float frameRate{30.0};
	uint32_t keyFrameInterval{0};
	OH_AVPixelFormat pixelFormat{AV_PIXEL_FORMAT_NV21};
	bool lowLatency{false};
};

class AvBufferInfo {
public:
	AvBufferInfo(int32_t indx, OH_AVBuffer *buff);
	~AvBufferInfo();
	uint8_t *AvBufferAddr();
	int32_t Attr(OH_AVCodecBufferAttr *attr);
	const OH_AVCodecBufferAttr *Attr();
	int32_t Index() const;
	uint32_t Flag();
	int64_t Pts();
	int32_t AvBufferSize();

private:
	int32_t index_{-1};
	OH_AVCodecBufferAttr attr_{0, 0, 0, AVCODEC_BUFFER_FLAGS_NONE};
	OH_AVBuffer *buff_{nullptr};
};

void convert_nv21_to_yuv420p(MSPicture *dest, uint8_t *buff);
void write_nv21_to_mspicture(MSPicture *pic, uint8_t *addr, int width, int height, int stride);
} // namespace ohos
#endif // OHOSDEC_COMMON
